class AnnorationsController < ApplicationController
    
    layout 'default'
    
    before_filter :login_required, :except => ['index', 'show', 'follow', 'browse', 'current', 'anonymous', 'create']
    
    # GET /annorations
    # GET /annorations.xml
    def index
        @page_title = "Newest Annorations"
        @pages = Page.recent_pages
        @tags = Page.top_tags
        
        respond_to do |format|
            format.html { render :action => "../default/index" }
            format.xml  { render :action => "../default/index", :xml => @page.to_xml }
        end
    end
    
    # GET /annorations/1
    # GET /annorations/1.xml
    def show
        @annoration = Annoration.find_by_uri(params[:u])
        
        
        respond_to do |format|
            format.html # show.rhtml
            format.xml  { render :xml => @annoration.to_xml }
        end
    end
    
    # GET /annorations/new
    def new
        @page_title = "Annorate a Page"
        
        # set up a site class for use by form helpers
        @title = params['t'] || "Untitled"
        @uri = params['u']
        
        # get popular and suggested tags
        annoration = Annoration.find(:first, :include => [:page], :conditions => ["user_id = ? AND uri = ?", current_user.id, @uri])
        if (annoration) 
            @new_annoration = false 
            page_id = annoration.page.id
            @rating = annoration.rating
            @comment = annoration.comment
            @user_tags = current_user.tags_for_page(page_id)
            @suggested_tags = current_user.suggested_tags_for_page(page_id, :limit => 8)
            @popular_tags = Page.popular_tags(page_id, :limit => 8)
            @editing_annoration = true
        else
            @new_annoration = true 
        end
        
        # bookmarklet dialog uses a custom chrome
        render(:layout => false)
    end
    
    # GET /annorations/anonymous_new
    ###################################
    # Add an anonymous entry into annorate
    def anonymous
        @page_title = "Annorate a Page"
        
        # set up a site class for use by form helpers
        @title = params['t'] || "Untitled"
        @uri = params['u']
        
        #Check for the cookie for this URI and do not allow creation if the cookie exists.
        @cookieExists = cookies[@uri]
        
        # get popular and suggested tags
        annoration = nil # Annoration.find(:first, :include => [:page], :conditions => ["user_id = ? AND uri = ?", current_user.id, @uri])
        if (annoration) 
            @new_annoration = false 
            page_id = annoration.page.id
            @rating = annoration.rating
            @comment = annoration.comment
            @user_tags = current_user.tags_for_page(page_id)
            @suggested_tags = current_user.suggested_tags_for_page(page_id, :limit => 8)
            @popular_tags = Page.popular_tags(page_id, :limit => 8)
            @editing_annoration = true
        else
            @new_annoration = true 
        end
        
        # bookmarklet dialog uses a custom chrome
        render(:layout => false)
    end
    
    ###################################
    # Update didily with a new relationship as paths are appended.
    def send_to_didily(from_uri, from_title, relation, to_uri, to_title)
        require 'net/http'
        require 'uri'
        
        key = Account::AccountConfiguration.config(:didily_api_key)
        uri = "http://scrumdidilyumptio.us/didilies"        
        res = Net::HTTP.post_form(URI.parse(uri), 
        {"key" => key,
                                    "didily[from_uri]" => from_uri,
                                    "didily[from_title]" => from_title,
                                    "didily[relation]" => relation,
                                    "didily[to_uri]" => to_uri,
                                    "didily[to_title]" => to_title
        })
    end
    
    # GET /annorations/1;edit
    def edit
        annoration = Annoration.find(params[:id])
        @editing_annoration = true
        @uri = annoration.page.uri
        @title = annoration.title
        @comment = annoration.comment
        @rating = annoration.rating
        @user_tags = current_user.tags_for_page(annoration.page.id)
        render(:partial => "edit", :layout => "default")
    end
    
    # POST /annorations
    # POST /annorations.xml
    def create
        
        # get the uri of the page being annorated
        uri = params[:annoration][:uri]
        
        # see if this user has annorated the page before
        @page = Page.find_by_uri(uri)
        
        # see if this user has annorated the page before, if the user is anonymous create a cookie
        # to limit the number of times they can annorate a page.
        if current_user
            @annoration = Annoration.find(:first, :include => [:page], :conditions => ["user_id = ? AND uri = ?", current_user.id, uri])
        else
            anon_user = User.find_by_login('anonymous')
            #@annoration = Annoration.find(:first, :include => [:page], :conditions => ["uri = ?", uri])
            cookies[uri] = { :value => uri, :expires => 30.days.from_now }
        end
        
        # the user has annorated this page before
        if @annoration
            details = params[:annoration]
            @annoration.uri = details[:uri]
            @annoration.title = details[:title]
            @annoration.comment = details[:comment]
            @annoration.rating = details[:rating]
            
            # first time this user has annorated the page
        else
            # create a new annoration for this page and user
            @annoration = Annoration.new(params[:annoration])
            @annoration.user_id = current_user.nil? ? anon_user.id : current_user.id
            @first_annoration = true
            # <uri> was rated by <user uri> 
            #send_to_didily(from_uri, from_title, relation, to_uri, to_title)
            if current_user
                send_to_didily(@annoration.uri, @annoration.title, "was annorated by", "http://www.annorate.com/users/" + current_user.login, current_user.login)
            else
                send_to_didily(@annoration.uri, @annoration.title, "was annorated by", "http://www.annorate.com/users/" + anon_user.login, anon_user.login)
            end
        end
        
        # see if the page has been annorated before
        send_to_didily(@annoration.uri, @annoration.title, "was annorated at", "http://www.annorate.com/pages/" + @annoration.page.id.to_s, "Annorations for " + @annoration.title) if !@page
        
        respond_to do |format|
            # try to save the annoration
            if @annoration.save
                
                # first time this page has been annorated
                if !@page 
                    @annoration.page.first_annoration_id = @annoration.id 
                    @annoration.page.save!
                end
                
                # ok, now we can update the tags
                if current_user
                    @annoration.page.update_user_tags(current_user.id, params[:page_tags])
                end
                
                # and the stats (for quick display) 
                @annoration.page.update_stats
                
                if current_user
                    
                    #flash[:notice] = 'Annoration was successfully created.'
                    format.html { redirect_to params[:redirect] || @annoration.uri }
                    format.xml  { head :created, :location => annoration_url(@annoration) }
                else
                    format.html { render :text => "<script>window.close();</script>" }
                end
            else
                format.html { render :action => "new" }
                format.xml  { render :xml => @annoration.errors.to_xml }
            end
        end
    end
    
    # PUT /annorations/1
    # PUT /annorations/1.xml
    def update
        @annoration = Annoration.find(params[:id])
        
        respond_to do |format|
            if @annoration.update_attributes(params[:annoration])
                flash[:notice] = 'Annoration was successfully updated.'
                format.html { redirect_to annoration_url(@annoration) }
                format.xml  { head :ok }
            else
                format.html { render :action => "edit" }
                format.xml  { render :xml => @annoration.errors.to_xml }
            end
        end
    end
    
    # DELETE /annorations/1
    # DELETE /annorations/1.xml
    def destroy
        @annoration = Annoration.find(params[:id])
        @annoration.destroy
        
        respond_to do |format|
            flash[:notice] = "Successfully deleted annoration."
            format.html { redirect_to params[:url] }
            format.xml  { head :ok }
        end
    end
end
